<?php

    /**
    * This is the model class for table "image".
    *
    * The followings are the available columns in table 'image':
    * @property string $id
    * @property string $name
    * @property string $image
    * @property string $view
    * @property string $desc
    * @property string $fb_like_count
    * @property string $fb_comment_count
    * @property string $created
    * @property string $user_id
    */
    class Image extends CActiveRecord
    {
        public $upload_method = 'file';
        public $image_file;
        public $image_url;
        public $crop_bottom;

        /**
        * Returns the static model of the specified AR class.
        * @param string $className active record class name.
        * @return Image the static model class
        */
        public static function model($className=__CLASS__)
        {
            return parent::model($className);
        }

        /**
        * @return string the associated database table name
        */
        public function tableName()
        {
            return 'image';
        }

        /**
        * @return array validation rules for model attributes.
        */
        public function rules()
        {
            // NOTE: you should only define rules for those attributes that
            // will receive user inputs.
            return array(
                array('name, created, user_id, status', 'required'),
                array('name, desc', 'length', 'max'=>255),
                array('view, fb_like_count, fb_comment_count, user_id, crop_bottom', 'length', 'max'=>10),
                // The following rule is used by search().
                // Please remove those attributes that should not be searched.
                array('status, id, name, desc, view, fb_like_count, fb_comment_count, created, user_id', 'safe', 'on'=>'search'),
            );
        }

        /**
        * @return array relational rules.
        */
        public function relations()
        {
            // NOTE: you may need to adjust the relation name and the related
            // class name for the relations automatically generated below.
            return array(
                'user' => array(self::BELONGS_TO, 'User', 'user_id'),
            );
        }

        /**
        * @return array customized attribute labels (name=>label)
        */
        public function attributeLabels()
        {
            return array(
                'id' => 'ID',
                'name' => 'Tên ảnh',
                'image' => 'Ảnh',
                'fb_like_count' => 'Fb Like Count',
                'fb_comment_count' => 'Fb Comment Count',
                'created' => 'Created',
                'user_id' => 'User',
                'desc' => 'Mô tả ngắn',
                'upload_method' => 'Kiểu upload',
            );
        }

        /**
        * Retrieves a list of models based on the current search/filter conditions.
        * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
        */
        public function search($mode = NULL)
        {
            // Warning: Please modify the following code to remove attributes that
            // should not be searched.

            $criteria=new CDbCriteria;

            $criteria->compare('id',$this->id,false);
            $criteria->compare('name',$this->name,true);
            $criteria->compare('image',$this->image,false);
            $criteria->compare('view',$this->view,false);
            $criteria->compare('fb_like_count',$this->fb_like_count,false);
            $criteria->compare('fb_comment_count',$this->fb_comment_count,false);
            $criteria->compare('created',$this->created,false);
            $criteria->compare('user_id',$this->user_id,false);
            $criteria->compare('status',$this->status,false);
            $criteria->compare('desc',$this->desc,false);
            $criteria->order = ($mode == 'random') ? 'rand()' : 'id DESC';

            return new CActiveDataProvider($this, array(
                'criteria'=>$criteria,
                'pagination'=>array(
                    'pageSize'=>10,
                ),
            ));
        }

        public function getStatusData(){
            return array(
                'APPROVED' => Yii::t('app', 'Approved'),
                'PENDING' => Yii::t('app', 'Pending'),
                'DISABLE' => Yii::t('app', 'Disable'),
            );
        }

        public function getIsApproved(){
            return $this->status == "APPROVED";
        }
        public function getIsPending(){
            return $this->status == "PENDING";
        }
        public function getIsDisable(){
            return $this->status == "DISABLE";
        }


        public function getUrl(){
            $params = array('id' => $this->id);
            return 'http://'.Yii::app()->params->domain.Yii::app()->createUrl('/hehe/web/image/view', $params); 
        }

        public function getUrlUpdate(){
            $params = array('id' => $this->id);
            return 'http://'.Yii::app()->params->domain.Yii::app()->createUrl('/hehe/web/image/update', $params); 
        }

        public function getImagePath($thumb = FALSE){ 
            $img_cnf = Yii::app()->params->image;
            $img_path = NULL;
            
            $img = $thumb ? $this->id.'_thumb.jpg' : $this->id.'_original.jpg';
//            return 'http://hehe.vn/'.$img_cnf['path'].$this->imageFolder.'/'.$img;
            
            if(file_exists($img_cnf['path'].$this->imageFolder.'/'.$this->id.'_original.jpg')){
                $img = $thumb ? $this->id.'_thumb.jpg' : $this->id.'_original.jpg';
                $img_path = 'http://'.Yii::app()->params->domain.'/'.$img_cnf['path'].$this->imageFolder.'/'.$img;
            }elseif($this->crawl_image){
                $img_path = $this->crawl_image;
            }else{
                $img_path = 'http://'.Yii::app()->params->domain.Yii::app()->createUrl('web/image/img', array('id' => $this->id));  
            }
            return $img_path;
        }

        public function getImageUrl($thumb = FALSE){
            $img_path = $this->getImagePath($thumb); 
            return $img_path ? $img_path : NULL;
        }

        public function getImageThumbUrl(){
            return $this->getImageUrl(TRUE);
        }


        public function getImageFolder($id = NULL){
            $id = $id ? $id : $this->id;
            for($i = 1000; $i <= 100000000; $i += 1000){
                if($id <= $i) return $i;
            }
        }     

        private $_newer;
        public function getNewer(){
            if($this->_newer) return $this->_newer;
            return $this->_newer = $this->find(new CDbCriteria(array(
                'condition' => "t.id > {$this->id} AND t.`status` = 'APPROVED'",
                'order' => 't.id ASC',
            )));
        }

        private $_older;
        public function getOlder(){
            if($this->_older) return $this->_older;
            return $this->_older = $this->find(new CDbCriteria(array(
                'condition' => "t.id < {$this->id} AND t.`status` = 'APPROVED'",
                'order' => 't.id DESC',
            )));
        }

        public function getIsAdminOwner(){
            if(Yii::app()->user->isGuest) return FALSE;
            if(Yii::app()->user->userInfo->isAdmin) return TRUE;
            $image = Image::model()->findByAttributes(array(
                'id' => $this->id,
                'user_id' => Yii::app()->user->id,
            ));
            return $image ? TRUE : FALSE;
        }
        public function getIsModOwner(){
            if(Yii::app()->user->isGuest) return FALSE;
            if(Yii::app()->user->userInfo->isMod) return TRUE;
            $image = Image::model()->findByAttributes(array(
                'id' => $this->id,
                'user_id' => Yii::app()->user->id,
            ));
            return $image ? TRUE : FALSE;
        }

        public function getNameEncode(){
            return CHtml::encode($this->name);
        }

        public function getCreatedTime(){
            $created = $this->reviewed ? $this->reviewed : $this->created;
            $format = date('G', strtotime($this->created)) ? 'G:i d/m/Y' : 'd/m/Y';
            return date($format, strtotime($created));
            //return MyDateTime::relative($this->created);
        }
        public function getUserName(){
            return $this->user ? $this->user->name : null;
        }


        public function postTwitter(){
            Yii::import('ext.TwitterOAuth.*');
            $tmhOAuth = new tmhOAuth(array(
                'consumer_key'      =>  'YCOVbNLMg2uukB4Qm22JSw',
                'consumer_secret'   =>  'y3vZcowOns91IvlTgPKBsw7FYCWxeJpghoNKe5jJk0',
                'user_token'        =>  '1114077866-HEUMt3hlvyRUkuIYpfkFmRyeO2jFUwhVeh5m8GF',
                'user_secret'       =>  'PP6sqtx4T1bS3fZVli8DQUHhxneERztv5B4tlUszW8c',
            ));    
            $code = $tmhOAuth->request('GET', $tmhOAuth->url('1/account/verify_credentials'));

            $limit = 95;
            $message = Myext::char_limiter($this->title.' '. $this->desc, $limit);
            $post = array(
                'status' => $message.' '.$this->url, 
                'lat' => '40.722803', 
                'long' => '-73.988514',
            );

            $image = $this->getImageUrl('small', TRUE);
            if(file_exists($image)){
                $post['media[]'] = "@{$image}"; 
            }
            $code = $tmhOAuth->request(
                'POST',
                'https://api.twitter.com/1.1/statuses/update_with_media.json',
                $post,
                true, // use auth
                true // multipart
            );
            return $code;
        } 


        
        public function getHaivlImageData($crawl_id = NULL){
            Yii::import('ext.simple_html_dom');
            
            $crawl_id = $crawl_id ? $crawl_id : $this->crawl_id;
            
            $url = "http://www.haivl.com/photo/{$crawl_id}";

            $html = new simple_html_dom($url); 

            $hasVideo = $html->find('.photoImg iframe', 0);
            $hasImg = $html->find('.photoImg img', 0);
            
            if(!$hasVideo && !$hasImg) return false;  

            
            
            $data = array();
            $data['name'] = Myext::textDecode($html->find('title', 0)->plaintext);

            $data['img'] = NULL;
            if($hasImg){
                $src = $html->find('.photoImg img', 0)->src;
                $add = strpos($src, 'http://') !== FALSE ? '' : 'http://www.haivl.com';
                $data['img'] = $add.$src;  
            }


            $data['view'] = str_replace('.', '', $html->find('.views .number', 0)->plaintext);
            preg_match('{(\d+)/(\d+)/(\d+)}', $html->find('.uploader', 0)->plaintext, $m);   //Đăng 7/5/2012 bởi 
            $data['created'] = $m ? "{$m[3]}-{$m[2]}-{$m[1]}" : date('Y-m-d H:i:s'); 
            $data['id'] = $crawl_id;

            $data['youtube'] = $hasVideo ? substr($html->find('.photoImg iframe', 0)->src, -11) : NULL;

            $html->clear();
            unset($html);
            
            return $data; 
        }

        
}